package cn.com.junitTest;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author liufl
 * @version 创建时间：2017年7月18日 下午3:20:40
 * 类说明
 */
public class JunitTest2 extends BaseJunit4Test {

	MockMvc mvc;  
	  
    @Autowired  
    WebApplicationContext webApplicationConnect;  
  
    String expectedJson;  
  
    @Before  
    public void setUp() throws JsonProcessingException {  
        mvc = MockMvcBuilders.webAppContextSetup(webApplicationConnect).build();  
    }  
  
    @Test
    @Transactional   //标明此方法需使用事务  
    @Rollback(false)  //标明使用完此方法后事务不回滚,true时为回滚 
    public void testGetSession() throws Exception {  
        String expectedResult = "login";  
        String uri = "/doLogin";//doLogin  
        MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON))  
                .andReturn();  
        int status = mvcResult.getResponse().getStatus();  
        String content = mvcResult.getResponse().getContentAsString();  
  
        Assert.assertTrue("正确的返回值为200", status == 200);  
        Assert.assertTrue("数据一致", expectedResult.equals(content));  
    }  
  
    protected String Obj2Json(Object obj) throws JsonProcessingException {  
        ObjectMapper mapper=new ObjectMapper();  
        return mapper.writeValueAsString(obj);  
    }  
}

